﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;


namespace RFW.Weather.Forecast
{
	public class Forecast : Communication
	{
		private string _locationCode = string.Empty;

		private List<Today> _today = null;
		public Moon Moon { get; set; }
		public List<Day> _days = null;

		public Forecast()
			: this("49120")
		{
		}

		public Forecast(string locationCode)
			: base(locationCode, "http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query={0}", true)
		{
		}

		public List<Today> Today
		{
			get { return _today; }
		}

		public List<Day> Days
		{
			get { return _days; }
		}

		public override void Process(XDocument results)
		{
			_today =
				(
					from today in results.Element("forecast").Element("txt_forecast").Elements("forecastday")
					select new Today
					{
						Period = Convert.ToInt16( today.Element("period").Value),
						Title = (string)today.Element("title") ?? string.Empty,
						Description = (string)today.Element("fcttext") ?? string.Empty,
						Icons = Icons.Linq(today.Element("icons"))
					}
				).OrderBy(s => s.Period).ToList();

			this.Moon = Moon.Linq(results.Element("forecast"));

			_days =
								(
					from day in results.Element("forecast").Element("simpleforecast").Elements("forecastday")
					select new Day
					{
						Date = Date.Linq(day.Element("date")),
						Conditions = day.Element("conditions").Value,
						SkyIcon = day.Element("skyicon").Value,
						High = Temperature.Linq(day.Element("high")),
						Low = Temperature.Linq(day.Element("low")),
						Icons = Icons.Linq(day.Element("icons"))
					}
				).OrderBy(s => s.Date.EPOCH).ToList();
		}

        public override void Process(string results)
        {
        }

		internal override void Failed()
		{
			_today = null;
		}
	}
}
